<template>
  <div>
    <!-- 会员收费名称 -->
    <div class="gl_mb_5">
      <el-row :gutter="20" class="gl_mt_15" type="flex" align="middle">
        <el-col :span="2" style="width: 160px;"><div style="font-size: 18px; font-weight: bold;">会员收费名称：</div></el-col>
        <el-col v-if="type === 'ok'" :span="20">
          <span>{{ memberFeeName }}</span>
          <el-button type="primary" size="mini" style="margin-left: 15px;" @click="type = 'edit'">编辑</el-button>
        </el-col>
        <el-col v-else :span="20">
          <el-input v-if="type === 'edit'" v-model="memberFeeName" size="mini" style="width:200px;" />
          <el-button type="primary" size="mini" style="margin-left: 15px;" @click="updateFeeName()">确定</el-button>
          <el-button type="default" size="mini" style="margin-left: 15px;" @click="cancleFeeName">取消</el-button>
        </el-col>
      </el-row>
    </div>
    <div v-if="editNotice" class="timeReminder"><span class="innerDots" />请完善该会员收费名称，若未完善，则会员设置不成功。</div>
    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="openAddMember()">新增会员</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe size="mini">
      <el-table-column prop="name" label="费用名称">
        <template slot-scope="{row}">
          <div v-if="!row.isEdit">{{ row.name }}</div>
          <el-input v-else v-model.trim="row.nameInput" :controls="false" size="mini" />
        </template>
      </el-table-column>
      <el-table-column prop="rangeYear" label="年限范围">
        <template slot-scope="{row}">
          <el-row v-if="!row.isEdit">
            <div v-if="row.minYear !== row.maxYear">
              <span>{{ row.minYear }}</span>
              <span> - </span>
              <span>{{ row.maxYear }}</span>
              <span>年</span>
            </div>
            <div v-else>
              <span>{{ row.minYear }}</span>
              <span>年</span>
            </div>
          </el-row>
          <el-row v-else type="flex" align="middle">
            <el-col :span="4"><el-input-number v-model.trim="row.minYearInput" :controls="false" size="mini" style="width:100%" /></el-col>
            <el-col :span="1" align="center">-</el-col>
            <el-col :span="4"><el-input-number v-model.trim="row.maxYearInput" :controls="false" size="mini" style="width:100%" /></el-col>
            <el-col :span="1" align="center">年</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格">
        <template slot-scope="{row}">
          <div v-if="!row.isEdit">
            <span>￥</span>
            <span>{{ formatMoney(row.price) }}</span>
            <span>/年</span>
          </div>
          <el-input-number v-else v-model.trim="row.priceInput" :precision="2" :min="0" :controls="false" size="mini" />
        </template>
      </el-table-column>
      <el-table-column prop="operating" label="操作" width="200">
        <template slot-scope="{row,$index}">
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickComplete(row)">完成</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)">取消</el-button>
          <el-button v-if="!row.isEdit" type="text" size="mini" @click="deleteItem(row,$index)">
            <span class="gl_color_error">删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子组件添加编辑 -->
    <test-form ref="testForm" fee-type="member" @pushTabelData="getTabelDate" @editTabelData="updataTabelDate" />
  </div>
</template>

<script>
import testForm from './editFee';
import {
  api_GET_TrainTrainningMembershipFee, // 获取培训会员费列表
  api_POST_TrainTrainningMembershipFee, // 新建会员费
  api_PUT_TrainTrainningMembershipFeeId, // 更新培训会员费
  api_DELETE_TrainTrainningMembershipFeeId, // 删除培训会员费
  api_GET_TrainTrainningMembershipFeeId, // 获取培训会员费
  api_GET_TrainTrainningSettingByTrainningIdTrainningId, // 按培训ID获取培训设置
  api_PUT_TrainTrainningSettingMembershipFeeTitleByTrainningIdTrainningId // 按培训ID更新会员费标题设置
} from '@/extend/api/trainswaggerApi/app.js';
import { Api_GET_TrainTrainningMembershipFeeQO } from '@/lib/form/train/swaggerForm.js';
export default {
  components: {
    testForm
  },
  data () {
    return {
      TrainningId: null,
      type: 'ok',
      editNotice: false,
      memberFeeName: '',
      originName: '', // 接口获取的会员收费名称
      qo: new Api_GET_TrainTrainningMembershipFeeQO(),
      tableData: [],
      loading: false,
      totalPage: 0
    };
  },
  created() {
    this.init();
    this.getPageList();
  },
  methods: {
    // 初始化
    init() {
      this.TrainningId = this.$route.params.id;
      this.getTrainingConfig();
    },
    // 获取数据
    getPageList() {
      // 手动转换0为null
      this.qo.MinPrice = null;
      this.qo.MinYear = null;
      this.qo.MaxPrice = null;
      this.qo.MaxYear = null;
      this.qo.TrainningId = this.$route.params.id;
      this.loading = true;
      api_GET_TrainTrainningMembershipFee(this.qo).then(
        res => {
          this.loading = false;
          if (res.items) {
            const _res = res.items || [];
            this.tableData = _res.map(item => {
              item.isEdit = false;
              item.nameInput = '';
              item.minYearInput = '';
              item.maxYearInput = '';
              item.priceInput = '';
              return item;
            });
            console.log('table', this.tableData);
          }
        }
      )
        .catch(
          error => {
            this.loading = false;
            this.$message({
              message: `列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取培训设置
    getTrainingConfig() {
      api_GET_TrainTrainningSettingByTrainningIdTrainningId(this.TrainningId).then(
        res => {
          if (res) {
            this.originName = res.membershipFeeTitle;
            this.memberFeeName = res.membershipFeeTitle;
            if (res.includeMembershipFees) {
              if (!(res.membershipFeeTitle && res.membershipFeeTitle !== '')) {
                this.editNotice = true;
              }
            }
          }
        }
      );
    },
    // 修改会员收费名称
    updateFeeName() {
      if (this.memberFeeName !== '') {
        if (this.memberFeeName.length <= 30) {
          api_PUT_TrainTrainningSettingMembershipFeeTitleByTrainningIdTrainningId(this.TrainningId, { title: this.memberFeeName }).then(
            res => {
              this.$message({
                message: '更新成功',
                type: 'success',
                showClose: true
              });
              this.originName = res.membershipFeeTitle;
              this.memberFeeName = res.membershipFeeTitle;
              this.type = 'ok'; // 更改状态
              this.editNotice = false;
            }
          ).catch(
            error => {
              this.$message({
                message: '获取信息失败' + error.error.message,
                type: 'error',
                showClose: true
              });
              this.memberFeeName = this.originName;
              this.type = 'ok'; // 更改状态
            }
          );
        } else {
          this.$message({
            message: '会员收费名称长度不能超过30个字符',
            type: 'error',
            showClose: true
          });
        }
      } else {
        this.$message({
          message: '会员收费名称不能为空',
          type: 'error',
          showClose: true
        });
      }
    },
    // 取消编辑会员费
    cancleFeeName() {
      this.memberFeeName = this.originName;
      this.type = 'ok';
    },
    // 新增会员
    openAddMember() {
      this.$refs.testForm.open();
    },
    // 编辑
    clickEidt(row, index) {
      api_GET_TrainTrainningMembershipFeeId(row.id).then(
        res => {
          row.nameInput = res.name;
          row.minYearInput = res.minYear;
          row.maxYearInput = res.maxYear;
          row.priceInput = this.formatMoney(res.price);
          row.isEdit = true;
        }
      ).catch(
        error => {
          this.$message({
            message: '获取信息失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 删除
    deleteItem(row, index) {
      this.$confirm(`您确定要删除${row.name}信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.postDelete(row);
          }
        );
    },
    postDelete(row) {
      api_DELETE_TrainTrainningMembershipFeeId(row.id).then(
        res => {
          this.$message({
            message: `删除成功`,
            type: 'success',
            showClose: true
          });
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: '删除失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 添加新信息
    getTabelDate(data) {
      data.trainningId = this.TrainningId;
      api_POST_TrainTrainningMembershipFee(data).then(
        res => {
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: '添加失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
      this.$refs.testForm.close();
    },
    // 修改信息
    updataTabelDate(data) {
      this.$refs.testForm.close();
    },
    // 点击完成
    clickComplete (row) {
      const _vo = {
        trainningId: row.trainningId,
        name: row.nameInput,
        price: this.yuanToFen(row.priceInput),
        minYear: row.minYearInput,
        maxYear: row.maxYearInput
      };
      if (_vo.minYear <= _vo.maxYear) {
        api_PUT_TrainTrainningMembershipFeeId(row.id, _vo).then(
          res => {
            this.$message({
              message: `更新成功`,
              type: 'success',
              showClose: true
            });
            this.getPageList();
            row.isEdit = false;
          }
        ).catch(
          error => {
            this.$message({
              message: `更新失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
            row.isEdit = false;
          }
        );
      } else {
        this.$message({
          message: `开始年限不得大于结束年限`,
          type: 'error',
          showClose: true
        });
      }
    },
    // 点击取消
    clickCancel (row) {
      row.isEdit = false;
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    }
  }
};
</script>

<style lang="scss" scoped>
.noBorder {
  border: none;
}
.timeReminder {
  padding-left: 150px;
  font-size: 14px;
  color: #DE1C1C;
  line-height: 18px;
  .innerDots {
    margin-right: 3px;
    display: inline-block;
    width:8px;
    height: 8px;
    background: #DE1C1C;
    border-radius: 50%;
  }
}
</style>
